package cn.qyd.threadpool;

import sun.plugin2.gluegen.runtime.CPU;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author 邱运铎
 * 异步处理通常涉及到IO操作，例如数据库查询或者文件的读写，属于IO密集型，线程池最大核心数设置 CPU核心数 * 2
 * @date 2024-03-23 1:05
 */
public class AsynchronousTaskProcessorUpgrade {
    private final static int CPU_CORE_COUNT = Runtime.getRuntime().availableProcessors();
    private final static int CORE_POOL_SIZE = CPU_CORE_COUNT * 2;
    private final static int MAX_POOL_SIZE = CPU_CORE_COUNT * 2 + 2;
    private final static ExecutorService exec = new ThreadPoolExecutor(CORE_POOL_SIZE,
            MAX_POOL_SIZE,
            60L,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(1000));

    public static void main(String[] args) {
        exec.execute(() -> {
            try {
                System.out.println("Async task is starting ");
                Thread.sleep(2000);
                System.out.println("Async task is computed ");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Main thread continues to exec other operations ");

        exec.shutdown();

    }
}
